package com.tool.sqlexecutor.sql;

import com.tool.sqlexecutor.config.DataSourceProperty;
import com.tool.sqlexecutor.util.SSHClient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.jdbc.datasource.init.DatabasePopulatorUtils;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Statement;
import java.util.List;
import java.util.concurrent.Callable;

public class SqlExecutor implements Callable<String> {
    private static final Log logger = LogFactory.getLog(SqlExecutor.class);
    private static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    private DataSourceProperty dataSourceProperty;
    private Resource sqlResource;
    private String separator;
    private boolean hasException;
    private String msg;

    public SqlExecutor(DataSourceProperty dataSourceProperty, Resource resource, String separator) {
        this.dataSourceProperty = dataSourceProperty;
        this.sqlResource = resource;
        this.separator = separator;
    }

    @Override
    public String call() throws Exception {
        SSHClient client = new SSHClient(dataSourceProperty.getSsh(), dataSourceProperty);
        try {
            client.start();
            DataSource dataSource = client.getDataSource();

            ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
            resourceDatabasePopulator.addScript(sqlResource);
            if (!StringUtils.isEmpty(separator)) {
                resourceDatabasePopulator.setSeparator(separator);
            }
            resourceDatabasePopulator.setSqlScriptEncoding("UTF-8");
            DatabasePopulatorUtils.execute(resourceDatabasePopulator, dataSource);
        } catch (Exception e) {
            logger.error(e);
            //e.printStackTrace();
            msg = e.getMessage();
            hasException = true;
        } finally {
            client.end();
        }

        return getResult();
    }

    private String getResult() {
        StringBuilder result = new StringBuilder().append("database:" + dataSourceProperty.getDatabase())
                .append("\n")
                .append("url:" + dataSourceProperty.getUrl())
                .append("\n");
        if (hasException) {
            return result.append("\tExecution failed!!").append("\n--------------------------------").toString();
        }
        return result.append("\tExecution Success").append("\n--------------------------------").toString();
    }

}
